let _Vue = null;
export default class VueRouterDemo {
  static install(Vue) {
    if (VueRouterDemo.install.installed) {
      return;
    }
    VueRouterDemo.install.installed = true;

    _Vue = Vue;

    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      },
    });
  }

  constructor(options) {
    this.options = options; // 记录构造函数中传入的选项
    this.routeMap = {}; // 把options中传入的路由规则解析出来,存储到routeMap, 键:储存的是路由地址,值:存储的是路由组件;
    this.data = _Vue.observable({
      current: window.location.pathname, // 存储当前路由地址
    });
  }

  init() {
    this.createRouteMap();
    this.initComponent(_Vue);
    this.initEvent();
  }

  // createRouteMap()的作用是把我们构造函数中传过来的选项中的路由规则,存储到routeMap对象中
  createRouteMap() {
    // 遍历所有的路由规则,把路由规则解析成键值对的形式,存储到routeMap对象中
    this.options.routes.forEach((route) => {
      this.routeMap[route.path] = route.component;
    });
  }

  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h(
          'a',
          {
            attrs: {
              href: this.to,
            },
            on: {
              click: this.clickHandler,
            },
          },
          [this.$slots.default]
        );
      },
      methods: {
        clickHandler(e) {
          history.pushState({}, '', this.to);
          this.$router.data.current = this.to;
          e.preventDefault();
        },
      },

    });
    const self = this;
    Vue.component('router-view', {
      render(h) {
        const component = self.routeMap[self.data.current];
        return h(component);
      },
    });
  }

  initEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname;
    });
  }
}
